//
//  HWRegisterView.m
//  嗨文
//
//  Created by 响当当 on 2019/3/19.
//  Copyright © 2019年 dongzheng. All rights reserved.
//

#import "HWRegisterView.h"
#import "HWCommonWebViewController.h"

@interface HWRegisterView ()<UITextFieldDelegate>
@property (nonatomic, strong)UIView *backGroundView;//背景
@property (nonatomic, strong)UITextField *phoneNumTextField;//手机号码输入
@property (nonatomic, strong)UITextField *phoenCodeTextField;//验证码输入
@property (nonatomic, strong)UITextField *codeTextField;//密码输入
@property (nonatomic, strong)UITextField *nameTextField;//昵称输入
@property (nonatomic, strong)UIButton *sendCodeMessageBtn;//发送短信验证码
@property (nonatomic, strong)UIButton *finishBtn;//完成按钮

@property (nonatomic, strong)UIButton *customerCodingBtn;//用户协议
@property (nonatomic, strong)UIButton *customerPrivideBtn;//隐私协议
@property (nonatomic, strong)UIButton *agreeImageBtn;//同意的图片

@property (nonatomic, strong)NSString *agreeCustomer;//同意用户协议
@end

@implementation HWRegisterView

- (UIView *)backGroundView
{
    if (!_backGroundView)
    {
        _backGroundView = [[UIView alloc]initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,200*kUIScaleBasePlus)];
        _backGroundView.backgroundColor = JSAMainColor;
    }
    return _backGroundView;
}

- (UITextField *)phoneNumTextField
{
    if (!_phoneNumTextField)
    {
        UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0,0,60*kUIScaleBasePlus,50*kUIScaleBasePlus)];
        leftView.backgroundColor= [UIColor clearColor];
        
        UIImageView *leftImageView = [[UIImageView alloc]initWithFrame:CGRectMake(19*kUIScaleBasePlus,16*kUIScaleBasePlus,12*kUIScaleBasePlus,18*kUIScaleBasePlus)];
        leftImageView.image = [UIImage imageNamed:@"telephone"];
        [leftView addSubview:leftImageView];
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(49*kUIScaleBasePlus,17*kUIScaleBasePlus,1*kUIScaleBasePlus,16*kUIScaleBasePlus)];
        lineView.backgroundColor = JSALineColor;
        [leftView addSubview:lineView];
        
        
        _phoneNumTextField = [[UITextField alloc]initWithFrame:CGRectMake(40*kUIScaleBasePlus,CGRectGetMaxY(self.backGroundView.frame)+25*kUIScaleBasePlus,SCREEN_WIDTH-80*kUIScaleBasePlus,50*kUIScaleBasePlus)];
        _phoneNumTextField.delegate = self;
        _phoneNumTextField.layer.masksToBounds = YES;
        _phoneNumTextField.layer.cornerRadius = 8;
        _phoneNumTextField.layer.borderColor = JSALineColor.CGColor;
        _phoneNumTextField.layer.borderWidth = 0.2;
        _phoneNumTextField.leftView = leftView;
        _phoneNumTextField.leftViewMode = UITextFieldViewModeAlways;
        _phoneNumTextField.placeholder = @"请输入手机号码";
        _phoneNumTextField.tag = 0;
    }
    return _phoneNumTextField;
}

- (UITextField *)phoenCodeTextField
{
    if (!_phoenCodeTextField)
    {
        UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0,0,60*kUIScaleBasePlus,50*kUIScaleBasePlus)];
        leftView.backgroundColor= [UIColor clearColor];
        
        UIImageView *leftImageView = [[UIImageView alloc]initWithFrame:CGRectMake(19*kUIScaleBasePlus,16*kUIScaleBasePlus,12*kUIScaleBasePlus,18*kUIScaleBasePlus)];
        leftImageView.image = [UIImage imageNamed:@"verification"];
        [leftView addSubview:leftImageView];
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(49*kUIScaleBasePlus,17*kUIScaleBasePlus,1*kUIScaleBasePlus,16*kUIScaleBasePlus)];
        lineView.backgroundColor = JSALineColor;
        [leftView addSubview:lineView];
        
        
        _phoenCodeTextField = [[UITextField alloc]initWithFrame:CGRectMake(40*kUIScaleBasePlus,CGRectGetMaxY(self.phoneNumTextField.frame)+15*kUIScaleBasePlus,SCREEN_WIDTH-80*kUIScaleBasePlus,50*kUIScaleBasePlus)];
        _phoenCodeTextField.delegate = self;
        _phoenCodeTextField.layer.masksToBounds = YES;
        _phoenCodeTextField.layer.cornerRadius = 8;
        _phoenCodeTextField.layer.borderColor = JSALineColor.CGColor;
        _phoenCodeTextField.layer.borderWidth = 0.2;
        _phoenCodeTextField.leftView = leftView;
        _phoenCodeTextField.leftViewMode = UITextFieldViewModeAlways;
        _phoenCodeTextField.placeholder = @"请输入验证码";
        _phoenCodeTextField.tag = 1;
        _phoenCodeTextField.secureTextEntry = YES;
    }
    return _phoenCodeTextField;
}

- (UITextField *)codeTextField
{
    if (!_codeTextField)
    {
        UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0,0,60*kUIScaleBasePlus,50*kUIScaleBasePlus)];
        leftView.backgroundColor= [UIColor clearColor];
        
        UIImageView *leftImageView = [[UIImageView alloc]initWithFrame:CGRectMake(19*kUIScaleBasePlus,16*kUIScaleBasePlus,12*kUIScaleBasePlus,18*kUIScaleBasePlus)];
        leftImageView.image = [UIImage imageNamed:@"password_edit"];
        [leftView addSubview:leftImageView];
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(49*kUIScaleBasePlus,17*kUIScaleBasePlus,1*kUIScaleBasePlus,16*kUIScaleBasePlus)];
        lineView.backgroundColor = JSALineColor;
        [leftView addSubview:lineView];
        
        
        _codeTextField = [[UITextField alloc]initWithFrame:CGRectMake(40*kUIScaleBasePlus,CGRectGetMaxY(self.phoenCodeTextField.frame)+15*kUIScaleBasePlus,SCREEN_WIDTH-80*kUIScaleBasePlus,50*kUIScaleBasePlus)];
        _codeTextField.delegate = self;
        _codeTextField.layer.masksToBounds = YES;
        _codeTextField.layer.cornerRadius = 8;
        _codeTextField.layer.borderColor = JSALineColor.CGColor;
        _codeTextField.layer.borderWidth = 0.2;
        _codeTextField.leftView = leftView;
        _codeTextField.leftViewMode = UITextFieldViewModeAlways;
        _codeTextField.placeholder = @"请输入密码";
        _codeTextField.tag = 2;
        _codeTextField.secureTextEntry = YES;
        [_codeTextField addTarget:self action:@selector(getUpKeyBoard:) forControlEvents:UIControlEventAllTouchEvents];
    }
    return _codeTextField;
}

- (UITextField *)nameTextField
{
    if (!_nameTextField)
    {
        UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0,0,60*kUIScaleBasePlus,50*kUIScaleBasePlus)];
        leftView.backgroundColor= [UIColor clearColor];
        
        UIImageView *leftImageView = [[UIImageView alloc]initWithFrame:CGRectMake(19*kUIScaleBasePlus,16*kUIScaleBasePlus,12*kUIScaleBasePlus,18*kUIScaleBasePlus)];
        leftImageView.image = [UIImage imageNamed:@"nickname"];
        [leftView addSubview:leftImageView];
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(49*kUIScaleBasePlus,17*kUIScaleBasePlus,1*kUIScaleBasePlus,16*kUIScaleBasePlus)];
        lineView.backgroundColor = JSALineColor;
        [leftView addSubview:lineView];
        
        
        _nameTextField = [[UITextField alloc]initWithFrame:CGRectMake(40*kUIScaleBasePlus,CGRectGetMaxY(self.codeTextField.frame)+15*kUIScaleBasePlus,SCREEN_WIDTH-80*kUIScaleBasePlus,50*kUIScaleBasePlus)];
        _nameTextField.delegate = self;
        _nameTextField.layer.masksToBounds = YES;
        _nameTextField.layer.cornerRadius = 8;
        _nameTextField.layer.borderColor = JSALineColor.CGColor;
        _nameTextField.layer.borderWidth = 0.2;
        _nameTextField.leftView = leftView;
        _nameTextField.leftViewMode = UITextFieldViewModeAlways;
        _nameTextField.placeholder = @"请输入用户昵称";
        _nameTextField.tag = 3;
        [_nameTextField addTarget:self action:@selector(getUpKeyBoard:) forControlEvents:UIControlEventAllTouchEvents];
    }
    return _nameTextField;
}

- (UIButton *)finishBtn
{
    if (!_finishBtn)
    {
        _finishBtn = [HWUtilties creatButtonWithFrame:CGRectMake(SCREEN_WIDTH/2-80*kUIScaleBasePlus,CGRectGetMaxY(self.nameTextField.frame)+25*kUIScaleBasePlus,160*kUIScaleBasePlus,48*kUIScaleBasePlus)
                                        textAligment:NSTextAlignmentCenter
                                                text:@"完成"
                                            textClor:[UIColor whiteColor]
                                           buttonBGC:JSAMainColor
                                            textFont:20*kUIScaleBasePlus
                                              target:self
                                              method:@selector(finish)];
        _finishBtn.layer.masksToBounds = YES;
        _finishBtn.layer.cornerRadius = _finishBtn.frame.size.height/2;
    }
    return _finishBtn;
}

- (UIButton *)sendCodeMessageBtn
{
    if (!_sendCodeMessageBtn)
    {
        _sendCodeMessageBtn = [HWUtilties creatButtonWithFrame:CGRectMake(SCREEN_WIDTH/2-80*kUIScaleBasePlus+130*kUIScaleBasePlus,CGRectGetMaxY(self.phoneNumTextField.frame)+25*kUIScaleBasePlus,80*kUIScaleBasePlus,30*kUIScaleBasePlus)
                                         textAligment:NSTextAlignmentCenter
                                                 text:@"发送验证码"
                                             textClor:JSAMainColor
                                            buttonBGC:[UIColor clearColor]
                                             textFont:10*kUIScaleBasePlus
                                               target:self
                                               method:@selector(sendCode)];
        
        _sendCodeMessageBtn.layer.masksToBounds = YES;
        _sendCodeMessageBtn.layer.cornerRadius = _sendCodeMessageBtn.frame.size.height/2;
        _sendCodeMessageBtn.layer.borderWidth = 1;
        _sendCodeMessageBtn.layer.borderColor = JSAMainColor.CGColor;
    }
    return _sendCodeMessageBtn;
}


- (UIButton *)agreeImageBtn
{
    if (!_agreeImageBtn)
    {
        _agreeImageBtn = [HWUtilties creatButtonWithFrame:CGRectMake(SCREEN_WIDTH/2-120*kUIScaleBasePlus-18*kUIScaleBasePlus,CGRectGetMaxY(self.finishBtn.frame)+15*kUIScaleBasePlus,18*kUIScaleBasePlus,18*kUIScaleBasePlus)
                                             textAligment:NSTextAlignmentCenter
                                                     text:@""
                                                 textClor:JSAMainColor
                                                buttonBGC:[UIColor clearColor]
                                                 textFont:12*kUIScaleBasePlus
                                                   target:self
                                                   method:@selector(changeSelect:)];
        [_agreeImageBtn setImage:[UIImage imageNamed:@"choose"] forState:UIControlStateNormal];
        _agreeImageBtn.selected = YES;
    }
    return _agreeImageBtn;
}

- (UIButton *)customerCodingBtn
{
    if (!_customerCodingBtn)
    {
        
        UILabel *titleLabel = [HWUtilties creatLabelWithFrame:CGRectMake(CGRectGetMaxX(self.agreeImageBtn.frame)+8*kUIScaleBasePlus,      CGRectGetMaxY(self.finishBtn.frame)+15*kUIScaleBasePlus,80*kUIScaleBasePlus,18*kUIScaleBasePlus)
                                                 textAligment:NSTextAlignmentLeft
                                                     textClor:LCHexColor(0x333333)
                                                     textFont:10*kUIScaleBasePlus];
        titleLabel.text = @"已同意并阅读了";
        [self addSubview:titleLabel];
        
        _customerCodingBtn = [HWUtilties creatButtonWithFrame:CGRectMake(CGRectGetMaxX(titleLabel.frame)-10*kUIScaleBasePlus,CGRectGetMaxY(self.finishBtn.frame)+15*kUIScaleBasePlus,80*kUIScaleBasePlus,18*kUIScaleBasePlus)
                                                 textAligment:NSTextAlignmentLeft
                                                         text:@"《用户协议》"
                                                     textClor:JSAMainColor
                                                    buttonBGC:[UIColor clearColor]
                                                     textFont:10*kUIScaleBasePlus
                                                       target:self
                                                       method:@selector(customerCoding)];
    }
    return _customerCodingBtn;
}

- (UIButton *)customerPrivideBtn
{
    if (!_customerPrivideBtn)
    {
        _customerPrivideBtn = [HWUtilties creatButtonWithFrame:CGRectMake(CGRectGetMaxX(self.customerCodingBtn.frame)-10*kUIScaleBasePlus,CGRectGetMaxY(self.finishBtn.frame)+15*kUIScaleBasePlus,90*kUIScaleBasePlus,18*kUIScaleBasePlus)
                                                  textAligment:NSTextAlignmentLeft
                                                          text:@"《隐私保护协议》"
                                                      textClor:JSAMainColor
                                                     buttonBGC:[UIColor clearColor]
                                                      textFont:10*kUIScaleBasePlus
                                                        target:self
                                                        method:@selector(customerPrivide)];
    }
    return _customerPrivideBtn;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self addSubview:self.backGroundView];
        [self addSubview:self.phoneNumTextField];
        [self addSubview:self.phoenCodeTextField];
        [self addSubview:self.sendCodeMessageBtn];
        [self addSubview:self.codeTextField];
        [self addSubview:self.nameTextField];
        [self addSubview:self.finishBtn];
        [self addSubview:self.agreeImageBtn];
        [self addSubview:self.customerCodingBtn];
        [self addSubview:self.customerPrivideBtn];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideKeyBoard)];
        [self addGestureRecognizer:tap];
        
        self.agreeCustomer = @"1";

    }
    
    return self;
}

#pragma mark - textfield
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [textField resignFirstResponder];
    
    [UIView animateWithDuration:0.5 animations:^{
        [self setY:NAVIBAR_HEIGHT];
    }];
    
    return YES;
}


- (void)sendCode
{
    [self hideKeyBoard];
    if ([HWUtilties checkTel:self.phoneNumTextField.text])
    {
        LCWeakSelf(weakSelf);
        [RegisterAndLoginManager getCodeWithPhone:self.phoneNumTextField.text Sucess:^(id  _Nonnull acceptData) {
            [weakSelf sentPhoneCodeTimeMethod];
        } fail:^(NSError * _Nullable error) {
            [SVProgressHUD showErrorWithStatus:error.description];
        }];
    }
}

#pragma 隐藏键盘
- (void)hideKeyBoard
{
    [self.phoneNumTextField resignFirstResponder];
    [self.phoenCodeTextField   resignFirstResponder];
    [self.codeTextField  resignFirstResponder];
    [self.nameTextField   resignFirstResponder];
    [UIView animateWithDuration:0.5 animations:^{
        [self setY:NAVIBAR_HEIGHT];
    }];
}

- (void)sentPhoneCodeTimeMethod
{
    //倒计时时间 - 60秒
    __block NSInteger timeOut = 59;
    //执行队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //计时器 -》dispatch_source_set_timer自动生成
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        if (timeOut <= 0) {
            dispatch_source_cancel(timer);
            //主线程设置按钮样式-》
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.sendCodeMessageBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                [self.sendCodeMessageBtn setUserInteractionEnabled:YES];
            });
        }else{
            //开始计时
            //剩余秒数 seconds
            NSInteger seconds = timeOut % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.1ld",seconds];
            //主线程设置按钮样式
            dispatch_async(dispatch_get_main_queue(), ^{
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1.0];
                [self.sendCodeMessageBtn setTitle:[NSString stringWithFormat:@"%@S后重新发送",strTime] forState:UIControlStateNormal];
                self.sendCodeMessageBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
                [UIView commitAnimations];
                //计时器件不允许点击
                [self.sendCodeMessageBtn setUserInteractionEnabled:NO];
            });
            
            timeOut--;
        }
    });
    
    dispatch_resume(timer);
}


//完成注册
- (void)finish
{
    [self hideKeyBoard];
    
    if ([self.agreeCustomer isEqualToString:@"0"])
    {
        [SVProgressHUD showErrorWithStatus:@"请先同意用户协议和隐私政策"];
        DISMISS_SVP(1.0f);
        return;
    }
    
    if (![HWUtilties checkTel:self.phoneNumTextField.text]) {
        return;
    }
    if (self.phoenCodeTextField.text.length != 4) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的验证码"];
        DISMISS_SVP(1.0f);
        return;
    }
    if (!self.codeTextField.text || self.codeTextField.text.length < 5) {
        [SVProgressHUD showErrorWithStatus:@"请5-14位的密码"];
        DISMISS_SVP(1.0f);
        return;
    }
    if (!self.nameTextField.text || self.nameTextField.text.length > 6 || [self.nameTextField.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请输入6位数的昵称"];
        DISMISS_SVP(1.0f);
        return;
    }
    NSDictionary *prarmers = @{
                               @"nickName" : self.nameTextField.text,
                               @"phoneNum" : self.phoneNumTextField.text,
                               @"code" : self.phoenCodeTextField.text,
                               @"password" : self.codeTextField.text
                               };
    
//    LCWeakSelf(weakSelf);
    [SVProgressHUD showWithStatus:nil];
    [RegisterAndLoginManager registUser:prarmers sucess:^(id  _Nonnull acceptData) {
        DISMISS_SVP(1.0f);
        [SVProgressHUD showSuccessWithStatus:@"创建账号成功"];
        UIViewController *topRootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        while (topRootViewController.presentedViewController)
        {
            topRootViewController = topRootViewController.presentedViewController;
        }
        
        [topRootViewController dismissViewControllerAnimated:YES completion:^{
            
        }];
    } fail:^(NSError * _Nullable error) {
        DISMISS_SVP(1.0f);
        [SVProgressHUD showErrorWithStatus:@"创建账号失败！"];
        DISMISS_SVP(1.0f);
    }];
}

- (void)getUpKeyBoard:(UITextField *)textField
{
    if (textField.tag == 2)
    {
        [UIView animateWithDuration:0.5 animations:^{
            [self setY:0];
        }];
    }
    else if (textField.tag == 3)
    {
        [UIView animateWithDuration:0.5 animations:^{
            [self setY:-50*kUIScaleBasePlus];
        }];
    }
}

- (void)changeSelect:(UIButton *)sender
{
    if (!sender.selected)
    {
        [sender setImage:[UIImage imageNamed:@"choose"] forState:UIControlStateNormal];
        sender.selected = YES;
        self.agreeCustomer = @"1";
    }
    else
    {
        [sender setImage:[UIImage imageNamed:@"unchoose"] forState:UIControlStateNormal];
        sender.selected = NO;
        self.agreeCustomer = @"0";
    }
}

- (void)customerCoding
{
    HWCommonWebViewController *tag = [[HWCommonWebViewController alloc]init];
    tag.urlStr = [NSString stringWithFormat:@"%@%@",WEBCOMME_HOST,@"/userAgreement"];
    tag.type = @"1";
    tag.titleStr = @"用户协议";
    tag.toUrl = nil;
    tag.toId = nil;
    tag.hidesBottomBarWhenPushed = YES;
    
    UIViewController *topRootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (topRootViewController.presentedViewController)
    {
        topRootViewController = topRootViewController.presentedViewController;
    }
    
    [topRootViewController presentViewController:tag animated:YES completion:nil];
}

- (void)customerPrivide
{
    HWCommonWebViewController *tag = [[HWCommonWebViewController alloc]init];
    tag.urlStr = [NSString stringWithFormat:@"%@%@",WEBCOMME_HOST,@"/privacyPolicy"];
    tag.type = @"1";
    tag.titleStr = @"用户隐私政策";
    tag.toUrl = nil;
    tag.toId = nil;
    tag.hidesBottomBarWhenPushed = YES;
    
    UIViewController *topRootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (topRootViewController.presentedViewController)
    {
        topRootViewController = topRootViewController.presentedViewController;
    }
    
    [topRootViewController presentViewController:tag animated:YES completion:nil];
}
@end
